from collections import defaultdict
from datetime import datetime
from operator import index

from blueBlog.extensions import db

# admin
class Admin(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20))
    password_hash = db.Column(db.String(128))
    blog_title = db.Column(db.String(100))
    blog_sub_title = db.Column(db.String(30))
    name = db.Column(db.String(30))
    about = db.Column(db.Text)

# 文章分类
class Category(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30), unique=True)
    posts = db.relationship('Post', back_populates='category')

# 文章模型
class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(60)) # 文章标题
    body = db.Column(db.Text) # 文章正文
    timestamp = db.Column(db.DateTime, default=datetime.utcnow) # 时间戳
    # 分类和文章间是一对多的关系(一个分类有多篇文章)
    category_id = db.Column(db.Integer, db.ForeignKey('category.id')) # 分类id, 外键
    category = db.relationship('Category', back_populates='posts')
    # 文章和评论间是一对多的关系(一篇文章有多个评论)
    comments = db.relationship('Comment', back_populates='post', cascade='all, delete-orphan')


# 评论模型
class Comment(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    author = db.Column(db.String(30)) # 作者名字
    email = db.Column(db.String(254)) # 电子邮件
    site = db.Column(db.String(255)) # 站点
    body = db.Column(db.Text) # 评论主题
    from_admin = db.Column(db.Boolean, default=False) # 是否是管理员的评论
    reviewed = db.Column(db.Boolean, default=False) # 是否审核通过(不通过不会显示在评论区中)
    timestamp = db.Column(db.DateTime, default=datetime.utcnow, index=True) # 时间戳
    post_id = db.Column(db.Integer, db.ForeignKey('post.id'))
    post = db.relationship('Post', back_populates='comments')
    # 评论回复, 回复评论本身也是一个评论
    # 同一个模型内的一对多关系在这里称为邻里关系表(Adjacency List Relationship)
    replied_id = db.Column(db.Integer, db.ForeignKey('comment.id')) # 外键，指向Comment的id
    replied = db.relationship('Comment', back_populates='replies', remote_side=[id])
    replies = db.relationship('Comment', back_populates='replied', cascade='all')

# 评论的回复可以新建一个表，如下👇，但回复本身也是评论。如上👆
# class Reply(db.Model):
#     pass